﻿
using PLCCommunication;
using PLCCommunication.Common.DataConvert;
using PLCCommunication.PLCType.Omron;
using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace PLC
{
    /// <summary>
    /// 欧姆龙FinsTCP通讯
    /// </summary>
    [Export("OmronFinsTCP", typeof(PlcReadWriteBase))]
    public class OmronFinsTCP : PlcReadWriteBase
    {
        private OmronFinsNet omronFinsNet = null;


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="pname"></param>
        /// <param name="iep"></param>
        /// <param name="timeout"></param>
        public OmronFinsTCP(int pid, string pname, IPEndPoint iep, int timeout = 10) :
            base(pid, pname, iep, timeout)
        {
            omronFinsNet = new OmronFinsNet();
            omronFinsNet.IpAddress = iep.Address.ToString();
            omronFinsNet.Port = iep.Port;
            omronFinsNet.DA2 = 0x00;// PLC单元号，通常为0
            omronFinsNet.ReadSplits = 999; //读取字长度，最长999，不能超过1000
            omronFinsNet.ByteTransform.DataFormat = PLCCommunication.Common.DataFormat.CDAB;
            omronFinsNet.ByteTransform.IsStringReverseByteWord = true;
            omronFinsNet.ConnectTimeOut = 2000;
            omronFinsNet.ReceiveTimeOut = 2000;
            IsConnected = false;
        }

        /// <summary>
        /// 启动与PLC链接
        /// </summary>
        /// <returns></returns>
        public override bool Connect(ref string msg)
        {
            bool res = false;
            try
            {
                if (!IsConnected)
                {
                    JYResult connect = omronFinsNet.ConnectServer();
                    if (connect.IsSuccess)
                    {
                        IsConnected = connect.IsSuccess;
                        byte num1 = this.omronFinsNet.SA1;
                        byte num2 = this.omronFinsNet.DA1;
                        msg = $"{num1},{num2}";
                        return true;
                    }
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 断开与PLC链接
        /// </summary>
        /// <returns></returns>
        public override bool Disconnect()
        {
            if (IsConnected)
            {
                JYResult connect = omronFinsNet.ConnectClose();
                IsConnected = false;
                return connect.IsSuccess;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// 读取BOOl变量
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public override bool ReadBool(string address)
        {
            JYResult<bool[]> result = omronFinsNet.ReadBool(address, 1);
            if (result.IsSuccess)
                return result.Content[0];
            else
                return false;

        }

        /// <summary>
        /// 读取16位整数
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public override short ReadInt16(string address)
        {
            JYResult<short> result = omronFinsNet.ReadInt16(address);
            if (result.IsSuccess)
                return result.Content;
            else
                return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public override Task<JYResult<short>> ReadInt16Async(string address)
        {
            JYResult<short> result = null;
            try
            {
                if (IsConnected)
                {
                    result = omronFinsNet.ReadInt16Async(address).Result;
                }
            }
            catch (Exception ex)
            {

            }
            return Task.FromResult(result);
        }

        /// <summary>
        /// 读取16位数组
        /// </summary>
        /// <param name="address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override short[] ReadArrInt16(string address, ushort length)
        {
            JYResult<byte[]> result = omronFinsNet.Read(address, length);
            if (result.IsSuccess)
                return ParseShortData(result.Content);
            else
                return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override async Task<JYResult<short[]>> ReadArrInt16Async(string address, ushort length)
        {
            JYResult<byte[]> result = await omronFinsNet.ReadAsync(address, length);
            if (result.IsSuccess)
            {
                short[] parsedData = ParseShortData(result.Content);
                return new JYResult<short[]> { Content = parsedData, IsSuccess = true };
            }
            else
            {
                return new JYResult<short[]> { IsSuccess = false, Message = result.Message };
            }
        }

        /// <summary>
        /// 读取32位整数
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public override int ReadInt32(string address)
        {
            JYResult<int> result = omronFinsNet.ReadInt32(address);
            if (result.IsSuccess)
                return result.Content;
            else
                return 0;
        }

        /// <summary>
        /// 读取Float单精度小数
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public override float ReadFloat(string address)
        {
            JYResult<float> result = omronFinsNet.ReadFloat(address);
            if (result.IsSuccess)
                return result.Content;
            else
                return 0.0f;
        }

        /// <summary>
        /// 读取Float数组
        /// </summary>
        /// <param name="address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override float[] ReadArrFloat(string address, ushort length = 0)
        {
            JYResult<byte[]> result = omronFinsNet.Read(address, length);
            if (result.IsSuccess)
                return ParseFloatData(result.Content);
            else
                return null;
        }


        /// <summary>
        /// 读取有符号16位数组
        /// </summary>
        /// <param name="address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private short[] ReadArrShort(string address, ushort length = 0)
        {
            JYResult<byte[]> result = omronFinsNet.Read(address, length);
            if (result.IsSuccess)
                return ParseShortData(result.Content);
            else
                return null;
        }
        /// <summary>
        /// 读取无符号16位数组
        /// </summary>
        /// <param name="address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private ushort[] ReadArrUshort(string address, ushort length = 0)
        {
            JYResult<byte[]> result = omronFinsNet.Read(address, length);
            if (result.IsSuccess)
                return ParseUshortData(result.Content);
            else
                return null;
        }


        private int[] ReadArrInt32(string address, ushort length = 0)
        {
            JYResult<byte[]> result = omronFinsNet.Read(address, length);
            if (result.IsSuccess)
                return ParseInt32Data(result.Content);
            else
                return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public override async Task<JYResult<int>> ReadInt32Async(string address)
        {

            JYResult<int> result = await omronFinsNet.ReadInt32Async(address);
            if (result.IsSuccess)
            {

                return new JYResult<int> { Content = result.Content, IsSuccess = true };
            }
            else
            {
                return new JYResult<int> { IsSuccess = false, Message = result.Message };
            }
        }

        /// <summary>
        /// 异步读取浮点数组
        /// </summary>
        /// <param name="address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override async Task<JYResult<float[]>> ReadArrFloatAsync(string address, ushort length)
        {
            JYResult<byte[]> result = await omronFinsNet.ReadAsync(address, length);
            if (result.IsSuccess)
            {
                float[] floats = ParseFloatData(result.Content);
                return new JYResult<float[]> { Content = floats, IsSuccess = true };
            }
            else
            {
                return new JYResult<float[]> { IsSuccess = false, Message = result.Message };
            }
        }


        private short[] ParseShortData(byte[] content)
        {
            int count = content.Length / 2;
            return Enumerable.Range(0, count)
                .Select(i => (short)ShortLib.GetShortFromByteArray(content, i * 2))
                .ToArray();
        }

        private ushort[] ParseUshortData(byte[] content)
        {
            int count = content.Length / 2;
            return Enumerable.Range(0, count)
                .Select(i => (ushort)UShortLib.GetUShortFromByteArray(content, i * 2))
                .ToArray();
        }

        private int[] ParseInt32Data(byte[] content)
        {
            int count = content.Length / 2;
            return Enumerable.Range(0, count)
                .Select(i => (Int32)IntLib.GetIntFromByteArray(content, i * 4))
                .ToArray();
        }

        private float[] ParseFloatData(byte[] content)
        {
            int count = content.Length / 4;
            return Enumerable.Range(0, count)
                .Select(i => (float)FloatLib.GetFloatFromByteArray(content, i * 4))
                .ToArray();
        }


        /// <summary>
        /// 读取PLC数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="address"></param>
        /// <param name="type"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public override T ReadValue<T>(string address, DataType type, ushort length = 0)
        {
            object obj = default(object);
            try
            {
                switch (type)
                {
                    case DataType.Bool:
                        obj = omronFinsNet.ReadBool(address);
                        break;
                    case DataType.Short:
                        obj = omronFinsNet.ReadInt16(address);
                        break;
                    case DataType.Int:
                        obj = omronFinsNet.ReadInt32(address);
                        break;
                    case DataType.Float:
                        obj = omronFinsNet.ReadFloat(address);
                        break;
                    case DataType.Double:
                        obj = omronFinsNet.ReadDouble(address);
                        break;
                    case DataType.String:
                        obj = omronFinsNet.ReadString(address, length);
                        break;
                    case DataType.ArrByte:
                        obj = omronFinsNet.Read(address, length);
                        break;
                    case DataType.ArrFloat:
                        //obj = ReadArrFloat(address, length);
                        obj = omronFinsNet.ReadFloat(address, length);
                        break;
                    case DataType.ArrShort:
                        obj = omronFinsNet.ReadInt16(address, length);
                        break;
                    case DataType.ArrUshort:
                        obj = omronFinsNet.ReadUInt16(address, length);
                        break;
                    case DataType.ArrInt:
                        obj = omronFinsNet.ReadUInt32(address, length);
                        break;
                    case DataType.ArrUint:
                        obj = omronFinsNet.ReadUInt32(address, length);
                        break;
                    default:
                        break;
                }
                return (T)obj;
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool WriteBool(string address, bool value)
        {
            bool[] data = new bool[1] { value };
            JYResult result = omronFinsNet.Write(address, value);
            return result.IsSuccess;
        }

        /// <summary>
        /// 写入16位整数
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        /// 
        public override bool WriteInt16(string address, short value)
        {
            JYResult result = omronFinsNet.Write(address, value);
            return result.IsSuccess;
        }
        /// <summary>
        /// 写入32位整数
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool WriteInt32(string address, int value)
        {
            JYResult result = omronFinsNet.Write(address, value);
            return result.IsSuccess;
        }

        /// <summary>
        /// 写入浮点数
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool WriteFloat(string address, float value)
        {
            JYResult result = omronFinsNet.Write(address, value);
            return result.IsSuccess;
        }


        /// <summary>
        /// 写入PLC数据
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public override JYResult WriteValue(string address, object value, DataType type = DataType.Short)
        {
            JYResult result = new JYResult();
            try
            {
                switch (type)
                {
                    case DataType.Bool:
                        result = omronFinsNet.Write(address, Convert.ToBoolean(value));
                        break;
                    case DataType.Short:
                        result = omronFinsNet.Write(address, Convert.ToInt16(value));
                        break;
                    case DataType.Int:
                        result = omronFinsNet.Write(address, Convert.ToInt32(value));
                        break;
                    case DataType.Float:
                        result = omronFinsNet.Write(address, Convert.ToSingle(value));
                        break;
                    case DataType.Double:
                        result = omronFinsNet.Write(address, Convert.ToDouble(value));
                        break;
                    case DataType.String:
                        result = omronFinsNet.Write(address, value.ToString());
                        break;
                    case DataType.ArrShort:
                        result = omronFinsNet.Write(address, value as short[]);
                        break;
                    case DataType.ArrUshort:
                        result = omronFinsNet.Write(address, value as ushort[]);
                        break;
                    case DataType.ArrByte:
                        result = omronFinsNet.Write(address, value as byte[]);
                        break;
                    default:
                        break;
                }
                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }


    }
}
